package cn.wolfcode.p2p.website.controller;

import cn.wolfcode.p2p.base.domain.RealAuth;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.excetion.DisplayableExcetion;
import cn.wolfcode.p2p.base.service.IRealAuthService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.util.AjaxResult;
import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.website.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

//实名认证
@Controller
public class RealAuthController {

    @Autowired
    private IRealAuthService realAuthService;
    @Autowired
    private IUserInfoService userInfoService;
    @Value("${file.path}")
    private String filePath;

    @RequestMapping("/realAuth")
    public String realAuth(Model model) {
        //判断用户是否已经实名认证userinfo.ishasrealauth
        UserInfo userInfo = userInfoService.getCurrent();
        if (userInfo.isHasRealAuth()) {
            //如果已经实名认证,跳转到realauto_result,设置auditing> = false
            model.addAttribute("auditing", false);
            RealAuth auth = realAuthService.get(userInfo.getRealAuthId());
            model.addAttribute("realAuth",realAuthService.get(userInfo.getRealAuthId()));
            return "/realAuth_result";
        } else {
            //如果没有实名认证,
            //判断userinfo中的realAuthId是否为null
            if (userInfo.getRealAuthId() == null) {
                //      如果为null,跳转到realauth
                return "/realAuth";
            }else {
                //如果不为null,跳转到realauth_result,设置auditing=true
                model.addAttribute("auditing", true);
                return "/realAuth_result";
            }
        }
    }

    //实名认证提交操作
    @RequestMapping("realAuth_save")
    @ResponseBody
    public AjaxResult realAuthSave(RealAuth realAuth) {
        AjaxResult result = null;
        try {
            realAuthService.apply(realAuth);
            result = new AjaxResult();
        } catch (DisplayableExcetion e) {
            e.printStackTrace();
            result = new AjaxResult(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult(false, "系统出错,请联系管理员");
        }
        return result;
    }

    //文件上传
    @RequestMapping("/uploadImage")
    @ResponseBody
    public String uploadImage(MultipartFile file){
        String imagePath = UploadUtil.upload(file, filePath);
        return imagePath;
    }



}
